package com.ozo.cloud.gateway.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaResponse;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.json.JSONUtil;
import com.ozo.cloud.common.base.model.ResultVO;
import com.ozo.cloud.gateway.config.properties.SecurityProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 鉴权配置
 *
 * @author qiangesoft
 * @date 2024-07-08
 **/
@RequiredArgsConstructor
@EnableConfigurationProperties(SecurityProperties.class)
@Configuration
public class SaTokenGatewayConfiguration {

    private final SecurityProperties securityProperties;

    /**
     * 注册过滤器
     */
    @Bean
    public SaReactorFilter saReactorFilter() {
        List<String> excludePathPatterns = securityProperties.getExcludePathPatterns();

        return new SaReactorFilter()
                // 指定拦截路由
                .addInclude("/**")
                // 指定放开路由
                .addExclude("/favicon.ico")
                // 设置鉴权的接口
                .setAuth(obj -> {
                    // 登录校验 -- 拦截所有路由
                    SaRouter.match("/**")
                            .notMatch(excludePathPatterns)
                            .check(r -> StpUtil.checkLogin());
                })
                // 异常处理
                .setError(e -> {
                    // 由于过滤器中抛出的异常不进入全局异常处理，所以此处统一转为JSON输出前端
                    SaResponse saResponse = SaHolder.getResponse();
                    saResponse.setHeader(Header.CONTENT_TYPE.getValue(), ContentType.JSON + ";charset=" + CharsetUtil.UTF_8);
                    return JSONUtil.parseObj(ResultVO.fail(e.getMessage()));
                })
                // 前置函数：在每次认证函数之前执行
                .setBeforeAuth(obj -> {
                    // 设置跨域响应头
                    SaHolder.getResponse()
                            // 浏览器默认XSS防护
                            .setHeader("X-XSS-Protection", "1; mode=block")
                            .setHeader("Access-Control-Allow-Origin", "*")
                            .setHeader("Access-Control-Allow-Credentials", "true")
                            .setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
                            .setHeader("Access-Control-Max-Age", "3600")
                            .setHeader("Access-Control-Allow-Headers", "*");

                    // 如果是预检请求，则立即返回到前端
                    SaRouter.match(SaHttpMethod.OPTIONS)
                            .free(r -> {
                            })
                            .back();
                });
    }

}
